package com.smart.aop.aspect;

import com.smart.common.utils.AuthUtil;
import com.smart.common.utils.ThreadLocalUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Aspect
@Component
public class PermissAspect {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Pointcut("@annotation(com.smart.common.annotation.PermissionCheck)")
    public void permissionCheck() {}

    @Before("permissionCheck()")
    public void before() {
        String userId = AuthUtil.getUserId();
        List<String> companyNames = new ArrayList<>();

        if (AuthUtil.isSuperAdmin()) {
            // 管理员查询所有公司名称（支持 sys_company_8 和 sys_company_8_1 格式）
            List<Map<String, Object>> adminResult = jdbcTemplate.queryForList(
                    "SELECT dict_name AS companyName " +
                            "FROM sys_dict " +
                            "WHERE is_deleted = '0' AND dict_code REGEXP '^sys_company_[0-9]+(_[0-9]+)?$'");
            for (Map<String, Object> map : adminResult) {
                companyNames.add((String) map.get("companyName"));
            }
        } else if (AuthUtil.isServiceProvider()) {
            // 服务商查询其层级下的公司名称
            String sql = "SELECT d.dept_name AS companyName " +
                    "FROM sys_dept d " +
                    "WHERE d.is_deleted = '0' AND d.id IN ( " +
                    "    SELECT child.id " +
                    "    FROM sys_dept child, sys_dept parent, sys_identity i " +
                    "    WHERE i.user_id = ? AND i.is_deleted = '0' AND parent.id = i.dept_id AND child.ancestors LIKE CONCAT('%,', parent.id))";
            List<Map<String, Object>> providerResult = jdbcTemplate.queryForList(sql, userId);
            for (Map<String, Object> map : providerResult) {
                companyNames.add((String) map.get("companyName"));
            }
        } else if (AuthUtil.isCompany() || AuthUtil.isBaoai()) {
            // 公司查询自己的名称
            String sql = "SELECT d.dept_name " +
                    "FROM sys_dept d " +
                    "JOIN sys_identity i ON d.id = i.dept_id " +
                    "WHERE i.user_id = ? AND i.is_deleted = '0' AND d.is_deleted = '0'";
            List<String> companyNamesList = jdbcTemplate.queryForList(sql, String.class, userId);
            if (!companyNamesList.isEmpty()) {
                companyNames.add(companyNamesList.get(0));
            }

        }

        // 将公司名称列表存储到上下文中
        ThreadLocalUtil.setPermissionResult(companyNames);
    }

    @After("permissionCheck()")
    public void after() {
        // 清除上下文数据
        ThreadLocalUtil.clear();
    }
}